<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">
          <a-col :md="4" :sm="8">
            <a-form-item label="车牌号">
              <a-input placeholder="请输入车牌号" v-model="queryParam.plateNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="有效期类型">
              <a-select v-model="queryParam.isForever" placeholder="有效期类型">
                <a-select-option :value="''">请选择异常类型</a-select-option>
                <a-select-option :value="0">自定义</a-select-option>
                <a-select-option :value="1">永久</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="创建时间">
              <a-date-picker placeholder="开始日期" @change="onChangeStartTime" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="创建时间">
              <a-date-picker placeholder="结束日期" @change="onChangeEndTime" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="车主/姓名">
              <a-input placeholder="名称模糊查询" v-model="queryParam.userName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="手机号">
              <a-input placeholder="可输入手机号尾号查询" v-model="queryParam.mobile"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button v-has="'parkUser:add'" @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('白名单')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete" />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择&nbsp;<a style="font-weight: 600">{{
          selectedRowKeys.length
        }}</a
        >项&nbsp;&nbsp;
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
        :scroll="{ x: 1400 }"
        style="word-break: break-all"
      >
        <span slot="action" slot-scope="text, record">
          <a v-has="'parkUser:add'" @click="handleEdit(record, operation.edit)">编辑</a>
          <a-divider v-has="'parkUser:add'" type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <parkWhiteList-modal ref="modalForm" @ok="modalFormOk"></parkWhiteList-modal>
    <ParkWhiteListModalDetail ref="detailForm"></ParkWhiteListModalDetail>
  </a-card>
</template>

<script>
import ParkWhiteListModal from './modules/ParkWhiteListModal'
import ParkWhiteListModalDetail from './modules/ParkWhiteListModalDetail'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { deleteAction, getAction, downFile } from '@api/manage'
import { filterObj } from '@/utils/util'

export default {
  name: 'ParkWhiteListList',
  mixins: [JeecgListMixin],
  components: {
    ParkWhiteListModal,
    ParkWhiteListModalDetail,
  },
  data() {
    return {
      description: '白名单管理页面',
      operation: {
        delay: 'delay',
        edit: 'edit',
      },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '停车场名称',
          align: 'center',
          dataIndex: 'parkName',
          width: 150,
        },
        {
          title: '车牌号',
          align: 'center',
          dataIndex: 'plateNo',
          width: 130,
        },
        {
          title: '客户姓名',
          align: 'center',
          dataIndex: 'userName',
          width: 120,
        },
        {
          title: '客户手机号码',
          align: 'center',
          dataIndex: 'mobile',
          width: 150,
        },
        {
          title: '是否永久',
          align: 'center',
          dataIndex: 'isForever',
          width: 150,
          customRender(value) {return value == 1 ? '是' : '否'},
        },
        {
          title: '开始日期',
          align: 'center',
          dataIndex: 'startDate',
          width: 150,
        },
        {
          title: '结束日期',
          align: 'center',
          dataIndex: 'endDate',
          width: 150,
        },
        {
          title: '开始时间',
          align: 'center',
          dataIndex: 'startTime',
          width: 150,
        },
        {
          title: '结束时间',
          align: 'center',
          dataIndex: 'endTime',
          width: 150,
        },
        {
          title: '周几有效',
          align: 'center',
          dataIndex: 'weekDay',
          width: 150,
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 180,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/whitelist/parkWhiteList/list',
        delete: '/whitelist/parkWhiteList/delete',
        deleteBatch: '/whitelist/parkWhiteList/deleteBatch',
        exportXlsUrl: '/whitelist/parkWhiteList/exportXls',
        importExcelUrl: '/whitelist/parkWhiteList/importExcel',
        carTypeList: '/ConfigCarType/configCarType/parkCarTypeList',
      },
      queryParam: {
        startTime: '',
        endTime: '',
        plateNo: '',
        parkNumber: '',
        carTypeId: '',
        type: '-1',
      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      CarTypeOptions: [{ value: '', label: '请选择车辆类型' }],
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  created() {
    this.keyupEnter()
  },
  mounted() {
    this.loadCarTypeOptions()
  },
  methods: {
    handleEdit: function (record, judge) {
      record.isForever = +record.isForever
      if (judge == this.operation.delay) {
        this.$refs.modalForm.edit(record, this.operation.delay)
        this.$refs.modalForm.title = '延期'
      } else {
        this.$refs.modalForm.edit(record, this.operation.edit)
        this.$refs.modalForm.title = '编辑'
      }
      this.$refs.modalForm.disableSubmit = false
      this.$refs.modalForm.carTypes = JSON.parse(JSON.stringify(this.CarTypeOptions))
      if (this.CarTypeOptions.length > 1) {
        this.$refs.modalForm.carTypes.shift()
      }
    },
    handleAdd: function () {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
      this.$refs.modalForm.carTypes = JSON.parse(JSON.stringify(this.CarTypeOptions))
      if (this.CarTypeOptions.length > 1) {
        this.$refs.modalForm.carTypes.shift()
        this.$refs.modalForm.defaultCarTypeId = this.$refs.modalForm.carTypes[0].value
      }
    },
    loadCarTypeOptions() {
      // const params = []
      // params.method = 'monthCar'
      getAction(this.url.carTypeList, { method: "monthCar" }).then((res) => {
        if (res.success && res.result.length > 0) {
          const CarArray = [{ value: '', label: '请选择车辆类型' }]
          res.result.forEach((car) => {
            CarArray.push({
              value: car.id,
              label: car.carTypeName,
            })
          })
          this.CarTypeOptions = CarArray
        }
      })
    },

    daysBetween(sDate1, sDate2) {
      let time1 = Date.parse(new Date(sDate1).toDateString())
      let time2 = Date.parse(new Date(sDate2).toDateString())
      let nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24))
      return nDays
    },

    handleExportXls(fileName) {
      let param = { ...this.queryParam }
      if (this.queryParam.startTime !== '' && this.queryParam.endTime !== '') {
        param.startTime = this.queryParam.startTime + ' 00:00:00'
        param.endTime = this.queryParam.endTime + ' 23:59:59'
        param.plateNo = this.queryParam.plateNo
      }
      if (this.queryParam.startTime !== '' && this.queryParam.endTime === '') {
        this.$message.error('请选择结束时间')
        return
      }
      if (this.queryParam.startTime === '' && this.queryParam.endTime !== '') {
        this.$message.error('请选择开始时间')
        return
      }
      if (this.queryParam.startTime !== '' && this.queryParam.endTime !== '') {
        if (this.queryParam.startTime > this.queryParam.endTime) {
          this.$message.error('开始时间不能大于结束时间')
          return
        }
      }

      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        }
      })
    },

    onChangeStartTime(date, dateString) {
      console.log(dateString);
      this.queryParam.startTime = dateString
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.endTime = dateString
    },

    loadData(arg) {
      const that = this
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let params = this.getQueryParams()
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          that.dataSource = res.result.records
          that.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        that.loading = false
      })
    },

    searchQuery() {
      let startTime = this.queryParam.startTime
      let endTime = this.queryParam.endTime
      if (startTime !== '' && endTime !== '') {
        if (startTime > endTime) {
          this.$message.error('开始时间不能大于结束时间')
          return
        }
      }
      if (startTime === '' && endTime !== '') {
        this.$message.error('请选择开始时间')
        return
      }

      if (startTime !== '' && endTime === '') {
        this.$message.error('请选择结束时间')
        return
      }
      this.loadData(1)
    },
    getQueryParams() {
      var param = Object.assign({}, this.isorter, this.queryParam)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      if (this.queryParam.startTime !== "" && this.queryParam.endTime !== "") {
        param.startTime = this.queryParam.startTime + " 00:00:00";
        param.endTime = this.queryParam.endTime + " 23:59:59";
      }
      return filterObj(param)
    },

    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function () {
            deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          },
        })
      }
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleDetail: function (record) {
      this.$refs.detailForm.title = '详情'
      this.$refs.detailForm.edit(record)
    },
    keyupEnter() {
      // eslint-disable-next-line no-unused-vars
      document.onkeydown = (e) => {}
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
